package models

import (
	"github.com/astaxie/beego/orm"
	"fmt"
)

type ConfigTopic struct {
	ChannelType int8 `orm:"column(channel_type)" description:"频道类型"`
	TopicType   int8 `orm:"column(topic_type)" description:"栏目类型"`
	BookId      int  `orm:"column(book_id);auto" description:"小说ID"`
	SortId      int  `orm:"column(sort_id)" description:"排序ID"`
}

func (t *ConfigTopic) TableName() string {
	return "config_topic"
}

func init() {
	orm.RegisterModel(new(ConfigTopic))
}

func GetAllConfigTopic() ([]*ConfigTopic, error) {
	o := orm.NewOrm()
	configTopics := make([]*ConfigTopic, 0)
	_, err := o.Raw("select * from config_topic order by sort_id asc").QueryRows(&configTopics)
	if err != nil {
		fmt.Println("select config_topic error.", err)
		return nil, err
	}
	return configTopics, nil
}

func GetConfigTopic(page int,pageSize int,cond *orm.Condition) ([]*ConfigTopic, int64) {
	o := orm.NewOrm()
	configTopics := make([]*ConfigTopic, 0)
	offset := (page - 1) * pageSize
	query := o.QueryTable(TableName("config_topic"))
	query = query.SetCond(cond)
	total, _ := query.Count()
	query.OrderBy("sort_id").Limit(pageSize, offset).All(&configTopics)

	return configTopics, total
}

func AddConfigTopic(bookId int,channel int8,topic int8) error{
	o := orm.NewOrm()
	sortIds := make([]int,0)
	o.Raw("select sort_id from config_topic where topic_type = ? and channel_type = ? order by sort_id desc",topic,channel).QueryRows(&sortIds)
	sortId := 1
	if len(sortIds) != 0 {
		sortId = sortIds[0] + 1
	}
	configTopic := &ConfigTopic{
		ChannelType:channel,
		TopicType:topic,
		BookId:bookId,
		SortId:sortId,
	}
	_, err := o.Insert(configTopic)
	if err != nil {
		return err
	}

	return nil
}

func UpdateConfigTopic(bookId int,channel int8,topic int8,sortId int) error{
	o := orm.NewOrm()
	_, err := o.Raw("UPDATE config_topic SET book_id = ? where channel_type = ? and topic_type = ? and sort_id = ?", bookId,channel,topic,sortId).Exec()
	if err != nil {
		return err
	}
	return nil
}

func DelConfigTopic(bookId int,channel int8,topic int8,sortId int) error{
	o := orm.NewOrm()
	_, err := o.Raw("delete from config_topic where book_id = ? and channel_type = ? and topic_type = ? and sort_id = ?", bookId,channel,topic,sortId).Exec()
	if err != nil {
		return err
	}
	return nil
}

func EmptyConfigTopic(channel int8,topic int8) error{
	o := orm.NewOrm()
	_, err := o.Raw("delete from config_topic where channel_type = ? and topic_type = ? ", channel,topic).Exec()
	if err != nil {
		return err
	}
	return nil
}
